package com.dmagic.cms.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dmagic.cms.common.annotation.FormModel;
import com.dmagic.cms.common.annotation.RequestJsonParam;
import com.dmagic.cms.common.controller.CommonController;
import com.dmagic.cms.common.query.ConditionsBean;
import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.util.JsonUtil;
import com.dmagic.cms.common.util.NumberUtil;
import com.dmagic.cms.common.util.StringUtil;
import com.dmagic.cms.entity.Language;
import com.dmagic.cms.entity.News;
import com.dmagic.cms.entity.UploadFileInfo;
import com.dmagic.cms.entity.Language.Lang;
import com.dmagic.cms.service.BaseService;
import com.dmagic.cms.service.NewsService;

@Controller
@RequestMapping(value = "/news")
public class NewsController extends CommonController {

	private String NEWS_LIST = "news/newsList";

	private String NEWS_ADD = "news/newsAdd";

	static {
	}

	@Autowired
	private BaseService baseService;

	@Autowired
	private NewsService newsService;

	@RequestMapping()
	public String list(Model model) {
		model.addAttribute("language", baseService.getAllLanguages());
		return NEWS_LIST;
	}

	@RequestMapping(value = "search", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String search(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
			@RequestParam String orderType, @RequestParam String orderBy,
			@RequestJsonParam("rules") List<ConditionsBean> conditions) throws Exception {
		PageUtil<Map> pageUtil = new PageUtil<Map>();
		pageUtil.setAutoCount(true);
		pageUtil.setPageNo(pageNo);
		pageUtil.setPageSize(pageSize);
		pageUtil.setOrder(orderType);
		pageUtil.setOrderBy(orderBy);
		pageUtil.setConditions(conditions);
		newsService.searchNews(pageUtil);
		return JsonUtil.toFullJsonWithDateFormat(pageUtil, DATE_FORMAT);
	}

	@RequestMapping("edit/{newsNo}")
	public String edit(@PathVariable("newsNo") String newsNo, @RequestParam("languageId") Long languageId,
			Model model) {
		List<News> news = newsService.getNewsByNewsNo(newsNo);
		List<Language> languages = baseService.getAllLanguages();
		lang: for (Language l : languages) {
			String languageKey = l.getLanguageKey();
			if (NumberUtil.equals(languageId, l.getLanguageId())) {
				model.addAttribute("defaultForm", languageKey);
			}
			for (News n : news) {
				if (l.getLanguageId() == n.getLanguageId()) {
					model.addAttribute(languageKey, n);
					List<UploadFileInfo> uploadFileInfo = baseService
							.getUploadFileInfoListByUploadFileSetInfoId(n.getUploadFileSetInfoId());
					model.addAttribute(languageKey + "_uploadFileInfo", uploadFileInfo);
					continue lang;
				}
			}
		}
		model.addAttribute("language", languages);
		return NEWS_ADD;
	}

	@ModelAttribute("preNews")
	public News getNews(Long newsId) {
		if (newsId == null) {
			return new News();
		}
		return newsService.getNews(newsId);
	}

	@RequestMapping("add")
	public String add(Model model) {
		News news = new News();
		news.setNewsNo(getDateFormatNo());
		model.addAttribute("defaultForm", Lang.zh_HK.getValue());
		model.addAttribute(Lang.zh_HK.getValue(), news);
		model.addAttribute(Lang.en.getValue(), news);
		model.addAttribute("language", baseService.getAllLanguages());
		return NEWS_ADD;
	}

	@RequestMapping("save")
	public String save(@FormModel("zh") News zhNews, @FormModel("en") News enNews,
			RedirectAttributes redirectAttributes) {
		newsService.saveNews(new News[] { zhNews, enNews });
		redirectAttributes.addFlashAttribute(SUCCESS, "Save Successful.");
		return "redirect:/news.do";
	}

	@RequestMapping("delete")
	@ResponseBody
	public String delete(@RequestJsonParam("newsIds") List<Long> newsIds) {
		newsService.deleteNews(newsIds);
		return "Delete Successful.";
	}

	@RequestMapping("delete/{newsId}")
	@ResponseBody
	public String delete(@PathVariable("newsId") Long newsId) {
		newsService.deleteNews(newsId);
		return "Delete Successful.";
	}

	@RequestMapping("top/{newsId}")
	@ResponseBody
	public String top(@PathVariable("newsId") Long newsId, @RequestParam("isTop") Boolean isTop) {
		News news = getNews(newsId);
		news.setIsTop(!isTop);
		newsService.saveNews(new News[] { news });
		return "Successful.";
	}

	@RequestMapping("publish/{newsId}")
	@ResponseBody
	public String publish(@PathVariable("newsId") Long newsId, @RequestParam("newsStatus") Boolean newsStatus) {
		News news = getNews(newsId);
		news.setNewsStatus(!newsStatus);
		newsService.saveNews(new News[] { news });
		return "Successful.";
	}

	@RequestMapping("web/newsDetail/{newsId}")
	public String getNewsById(@PathVariable("newsId") Long newsId, @RequestParam Long languageId, Model model) {
		News news = getNews(newsId);
		model.addAttribute("news", news);
		model.addAttribute("language", languageId);		
		return "web/news/newsDetail";
	}
	
	@RequestMapping("web/heatMap/{newsId}")
	public String getNews(@PathVariable("newsId") Long newsId, @RequestParam Long languageId, Model model) {
		News news = getNews(newsId);
		model.addAttribute("news", news);
		model.addAttribute("language", languageId);
		return "web/news/newsDetail";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder b) {
		DateFormat fmt = new SimpleDateFormat(DATE_FORMAT);
		CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
		b.registerCustomEditor(Date.class, "newsDate", dateEditor);
	}
}
